<template>
  <div>
    <ETable ref="tableRef" :loading="loading" :columns="columns" :data="data.list" :total="data.total"
      @onPageChange="onPageChange">
      <template #handler="{ scope }">
        <el-button link type="primary" @click="onCheck(scope.row)">查看</el-button>
        <el-button link type="danger" :loading="scope.row.loading" @click="onRemove(scope.row)">删除</el-button>
      </template>
    </ETable>
  </div>
</template>

<script setup>
import { getArticleList, deleteArticle } from '@/api/article.js'
import { ref, onActivated } from 'vue'
import { useRequest } from 'vue-request'
import ETable from '@/components/e-table/index.vue'
import { ElMessage } from 'element-plus'
import router from '@/router'

const tableRef = ref()

const columns = ref([
  { label: '排名', prop: 'ranking' },
  { label: '标题', prop: 'title' },
  { label: '作者', prop: 'author' },
  { label: '发布时间', prop: 'publicDate' },
  { label: '内容简介', prop: 'desc' },
  { label: '操作', prop: 'handler', template: true }
])

onActivated(() => {
  getList({
    pageNo: tableRef.value.pageNo
  })
})

const {
  data,
  loading,
  run: getList
} = useRequest(
  async (_data) => {
    const data = {
      page: _data?.pageNo ?? 1,
      size: _data?.pageSize ?? tableRef.value?.pageSize ?? 10
    }
    if (_data?.pageNo === 1) {
      tableRef.value.initPageNo()
    }
    const res = await getArticleList(data)
    console.log(res)
    return res
  },
  {
    initialData: { list: [], total: 0 },
    manual: true
  }
)

const onPageChange = (pageNo, pageSize) => {
  getList({
    pageNo,
    pageSize
  })
}

const onCheck = (row) => {
  router.push({
    name: 'article-read',
    params: { id: row._id }
  })
}
const onRemove = (row) => {
  row.loading = true
  deleteArticle(row._id)
    .then(() => {
      ElMessage.success('删除成功')
      getList({ pageNo: 1 })
    })
    .finally(() => {
      row.loading = false
    })
}
</script>

<style lang="scss" scoped></style>
